package com.hysoft.pdr.main.service.controller;

import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.hysoft.pdr.entity.common.RequestCondition;
import com.hysoft.pdr.main.service.service.ICreateEntityService;

@RestController
@RequestMapping("/pg")
public class CreateEntityController {
	@Autowired
	private ICreateEntityService ICreateEntityService;

	@RequestMapping(value = "/getAllTablesJavaBean")
	public Object getAllTablesJavaBean(@RequestBody RequestCondition params, HttpServletRequest request) {
		Map<String, Object> param = params.getFilter();
		String directory = "C:\\java_entity";
		if (param.get("directory") != null) {
			directory = param.get("directory").toString();
		}

		// 匹配将那些表导出生成java实体类
		if (param.get("table") == null) {
			param.put("table", "pflood");
		}
		List<Map<String, Object>> tables = ICreateEntityService.queryAllTables(params);

		// java文件的package
		String packageurl = "package com.sgcc.nrxt.pms.tech.preventfloodpc.api.entry;";
		if (param.get("package") != null) {
			packageurl = param.get("package").toString();
		}
		String resourcedata = "@Data";
		String resourceequ = "@EqualsAndHashCode(callSuper = false)";
		String resourceacc = "@Accessors(chain = true)";
		// 表空间名称
		String reousrcetablespace = "power tn";
		if (param.get("tablespace") != null) {
			reousrcetablespace = param.get("tablespace").toString();
		}
		for (Map<String, Object> map : tables) {
			List<String> result = new ArrayList<>();
			result.add(packageurl);

			result.add("import java.io.Serializable;");
			result.add("import java.util.Date;");

			result.add("import com.baomidou.mybatisplus.annotation.IdType;");
			result.add("importcom.baomidou.mybatisplus.annotation.TableField;");
			result.add("import com.baomidou.mybatisplus.annotation.TableId;");
			result.add("importcom.baomidou.mybatisplus.annotation.TableName;");
			result.add("importcom.baomidou.mybatisplus.extension.activerecord.Model;");
			result.add("importcom.fasterxml.jackson.annotation.JsonFormat;");

			result.add("import io.swagger.annotations.ApiModelProperty;");
			result.add("import lombok.Data;");
			result.add("import lombok.EqualsAndHashCode;");
			result.add("import lombok.experimental.Accessors;");

			result.add(resourcedata);
			result.add(resourceequ);
			result.add(resourceacc);

			param.put("tablename", map.get("relname"));

			String resourcetable = "@TableName(" + "\"" + reousrcetablespace + "." + map.get("relname") + "\"" + ")";
			result.add(resourcetable);

			String javaname = dealUnloadLine(map.get("relname").toString());
			String namepre = javaname.substring(0, 1);
			String nameend = javaname.substring(1, javaname.length());
			String javanameNew = namepre.toUpperCase() + nameend;

			String entityfirst = "public class" + javanameNew + "extends Model<" + javanameNew + "> {";
			result.add(entityfirst);

			List<Map<String, Object>> columns = ICreateEntityService.queryAllColumns(params);

			List<String> setAndGet = new ArrayList<>();

			for (Map<String, Object> column : columns) {
				String type = column.get("type").toString();
				String name = column.get("attname").toString();
				String comment = "";
				if (column.get("comment") != null) {
					comment = "\"" + column.get("comment").toString() + "\"";
				}

				String col = "\"" + column.get("attname").toString() + "\"";

				String ApiModelProperty = "@ApiModelProperty(value =" + comment + ")";
				String TableField = "@TableField(value = " + col + ")";

				name = dealUnloadLine(name);
				if (type.contains("character varying")) {
					result.add("               ");
					if ("id".equals(name)) {
						result.add(ApiModelProperty);
						result.add("@TableId(value = \"id\",type = IdType.INPUT)");
						String out = "private string " + name + ";";
						result.add(out);
						result.add("        ");
						result.add("@Override");
						result.add("public Serializable pkVal() {");
						result.add("return this.id;");
						result.add("}");
					} else {
						result.add(ApiModelProperty);
						result.add(TableField);
						String out = "private string " + name + ";";
						result.add(out);
					}
				} else if (type.contains("timestamp(6)")) {
					result.add("             ");
					result.add(ApiModelProperty);
					result.add(TableField);
					String timems = "@JsonFormat(pattern=\"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")";
					result.add(timems);
					String out = "private Date " + name + ";";
					result.add(out);
					setAndGet.add(name);
				} else if (type.contains("integer")) {
					result.add("             ");
					result.add(ApiModelProperty);
					result.add(TableField);
					String out = "private Integer " + name + ";";
					result.add(out);
				} else if (type.contains("numeric")) {
					result.add("         ");
					result.add(ApiModelProperty);
					result.add(TableField);
					String out = "private float " + name + ";";
					result.add(out);
				} else {
					if ("-".equals(type)) {
						continue;
					}
					String out = ">>>>>>>>>>>>>>>>" + map.get("relname").toString() + "的" + name + "类型为:" + type
							+ "无法识别";
					result.add(out);
				}
			}
			result.add("");
			// 针对事件添加setget方法
			timeSetAndGet(setAndGet, result);
			result.add("}");
			wirteFileToLocal(result, javanameNew, map.get("relname").toString(), directory);
		}
		return "success";
	}

	/**
		*
		* */
	@RequestMapping(value = "/getSingleTablesJavaBean")
	public Object getSingleTablesJavaBean(@RequestBody RequestCondition params, HttpServletRequest request) {
		Map<String, Object> param = params.getFilter();
		String directory = "C:\\java entity";
		if (param.get("directory") != null) {
			directory = param.get("directory").toString();
		}

		String resourcedata = "@Data";
		String resourceequ = "@EqualsAndHashCode(callSuper = false)";
		String resourceacc = "@Accessors(chain =true)";
		// 表空间名称
		String reousrcetablespace = "power tn";
		if (param.get("tablespace") != null) {
			reousrcetablespace = param.get("tablespace").toString();
		}
		// java文件的package
		String packageurl = "packagecom.sgcc.nrxt.pms.tech.preventfloodpc.api.entry;";
		if (param.get("package") != null) {
			packageurl = param.get("package").toString();
		}
		List<String> result = new ArrayList<>();
		result.add(packageurl);
		result.add("import java.io.Serializable;");
		result.add("import java.util.Date;");
		result.add("importcom.baomidou.mybatisplus.annotation.IdType;");
		result.add("importcom.baomidou.mybatisplus.annotation.TableField;");
		result.add("importcom.baomidou.mybatisplus.annotation.TableId;");
		result.add("importcom.baomidou.mybatisplus.annotation.TableName:");
		result.add("importcom.baomidou.mybatisplus.extension.activerecord.Model;");
		result.add("importcom.fasterxm1.jackson.annotation.JsonFormat;");

		result.add("import io.swagger.annotations.ApiModelProperty;");
		result.add("import lombok.Data;");
		result.add("import lombok.EqualsAndHashCode:");
		result.add("import lombok.experimental.Accessors;");

		result.add(resourcedata);
		result.add(resourceequ);
		result.add(resourceacc);
		param.put("tablename", param.get("relname"));

		String resourcetable = "@TableName(" + "\"" + reousrcetablespace + "." + param.get("relname") + "\"" + ")";
		result.add(resourcetable);

		String javaname = dealUnloadLine(param.get("relname").toString());
		String namepre = javaname.substring(0, 1);
		String nameend = javaname.substring(1, javaname.length());
		String javanameNew = namepre.toUpperCase() + nameend;

		String entityfirst = "publicclass" + javanameNew + "extends Model<" + javanameNew + "> {";
		result.add(entityfirst);

		List<Map<String, Object>> columns = ICreateEntityService.queryAllColumns(params);

		List<String> setAndGet = new ArrayList<>();

		for (Map<String, Object> column : columns) {
			String type = column.get("type").toString();
			String name = column.get("attname").toString();
			String comment = "";

			if (column.get("comment") != null) {
				comment = "\"" + column.get("comment").toString() + "\"";
			}

			String col = "\"" + column.get("attname").toString() + "\"";

			String ApiModelProperty = "@ApiModelProperty(value = " + comment + ")";
			String TableField = "@TableField(value = " + col + ")";
			name = dealUnloadLine(name);

			if (type.contains("character varying")) {
				result.add("   ");
				if ("id".equals(name)) {
					result.add(ApiModelProperty);
					result.add("@TableId(value = \"id\", type = IdType.INPUT)");
					String out = "private string " + name + ";";
					result.add(out);
					result.add("   ");
					result.add("@Override");
					result.add("public Serializable pkVal() {");
					result.add("return this.id;");
					result.add("}");
				} else {
					result.add(ApiModelProperty);
					result.add(TableField);
					String out = "private String " + name + ";";
					result.add(out);
				}
			} else if (type.contains("timestamp(6)")) {
				result.add("       ");
				result.add(ApiModelProperty);
				result.add(TableField);
				String timems = "@JsonFormat(pattern=\"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")";
				result.add(timems);
				String out = "private Date " + name + ";";
				result.add(out);
				setAndGet.add(name);
			} else if (type.contains("integer")) {
				result.add("     ");
				result.add(ApiModelProperty);
				result.add(TableField);
				String out = "private Integer " + name + ";";
				result.add(out);
			} else if (type.contains("numeric")) {
				result.add("   ");
				result.add(ApiModelProperty);
				result.add(TableField);
				String out = "private float " + name + ";";
				result.add(out);
			} else {
				if ("-".equals(type)) {
					continue;
				}
				String out = ">>>>>>>>>>>>>>>>" + param.get("relname").toString() + "的" + name + "类型为:" + type + "无法识别";
				result.add(out);
			}
		}
		result.add(" ");
		// 针对事件添加setget方法
		timeSetAndGet(setAndGet, result);
		result.add("}");
		wirteFileToLocal(result, javanameNew, param.get("relname").toString(), directory);
		return "success";
	}

	private void timeSetAndGet(List<String> list, List<String> result) {
		for (String name : list) {
			String namePre = name.substring(0, 1);
			String nameEnd = name.substring(1, name.length());
			String nameNew = namePre.toUpperCase() + nameEnd;
			result.add("public Date get" + nameNew + "() {");
			result.add("return" + name + "== null ? null :(Date)" + name + ".clone();");
			result.add("}");
			result.add("");
			result.add("public void set" + nameNew + "(Date " + name + "){");
			result.add("this." + name + "=" + name + "== null ? null :(Date)" + name + ".clone();");
			result.add("}");
		}
	}

	private void wirteFileToLocal(List<String> list, String filename, String tablename, String directory) {
		String path = directory;
		filename = filename + ".java";
		File file = new File(path);
		// File[l files = file.listFiles();
		// for (File a :files){
		// System.err.println(a.getName());
		// }
		if (!file.exists()) {
			file.mkdirs();
		}

		File filejava = new File(path + File.separator + filename);
		FileWriter fw = null;
		try {
			fw = new FileWriter(filejava, true);
			for (String str : list) {
				if (str.contains("(value =)")) {
					str = str.replaceAll("value = ", "value = \"\"");
				}
				fw.write(str);
				fw.write("\n");
			}
			fw.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fw != null) {
				try {
					fw.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	// public static void main(string[] args){
	// string abc = "province org id name";
	// System.err.println(dealUnloadLine(abc));
	// }
	private String dealUnloadLine(String name) {
		String search = "_";
		int count = 0;
		int length = name.length();
		String newname = name.replaceAll(search, "");
		int newLength = newname.length();
		count = length - newLength;
		if (count > 0) {
			int first = name.indexOf(search);
			name = method(name, first);
			for (int i = 1; i < count; i++) {
				int next = name.indexOf(search, first + 1);
				if (next > 0) {
					name = method(name, next);
					first = next;
				}
			}
			return name;
		} else {
			return name;
		}
	}

	private String method(String name, int flag) {
		String replace = name.substring(flag, flag + 2);
		String replaceNew = replace.toUpperCase().replace("", "");
		return name.replaceAll(replace, replaceNew);
	}
}
